import { TreeList } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import { deepClone } from '~/public/cpas-business/tools/Tools';
import DevPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup/DevPopup';
import { getAccountInfo } from '../product/YearAnalysis/server';
import { updateBB_BasType } from './server';
const TreeListPrice = forwardRef((props: any, ref: any) => {
  const treeList = useRef<any>();
  const { initialState } = useModel('@@initialState');
  const [Dis, setDis] = useState(true);
  const olddata = useRef<any>([]);
  const SelectRow = useRef<any>();
  const LastUpdate = useRef<any>();
  const [goodsType, setGoodsType] = useState<any[]>();
  const [IsViewSet, setIsViewSet] = useState(false);
  const [IsViewAlert, setIsViewAlert] = useState(false);
  const InputRef = useRef<any>();
  const { dbname, sjnd } = initialState?.curPart as any;

  /**
   * ok 按钮点击
   */
  const OnClickOK = async () => {
    treeList.current?.instance.saveEditData();
    let isChang = false;
    goodsType?.forEach((a: any) => {
      let d = olddata.current.filter(
        (b: any) => b.AuditTestCostMehthod === a.AuditTestCostMehthod && a.name === b.name,
      );
      if (d.length == 0) {
        isChang = true;
      }
    });

    if (isChang) {
      setIsViewAlert(true);
    }
    setIsViewSet(false);
  };

  const OKClickComputer = async () => {
    await addMehthod();
    await props.updateComputer();
  };

  /***
   * 更新
   */
  const addMehthod = async () => {
    let data: any = goodsType?.map((v: any) => {
      return {
        AuditTestCostMehthod: v.AuditTestCostMehthod,
        rowState: 'update',
        where: { typeID: v.id },
      };
    });

    let res = await updateBB_BasType(dbname, data, 'BAS_Product');
    let res_type = await updateBB_BasType(dbname, data, 'BAS_Product_Type');
    if (res.success && res_type.success) {
      setIsViewAlert(false);
      notify('更新成功', 'success', 1000);
    } else {
      notify('更新失败', 'error', 1000);
    }
  };

  const OnClickButhSet = () => {
    debugger;
    if (treeList.current._instance.hasEditData()) {
      treeList.current._instance.saveEditData();
    }

    if (LastUpdate.current) {
      setGoodsType(
        goodsType?.map((a: any) => {
          let c = SelectRow.current?.filter((b: any) => b.id === a.id);
          if (c.length) {
            return { ...a, AuditTestCostMehthod: LastUpdate.current.AuditTestCostMehthod };
          } else {
            return { ...a };
          }
        }),
      );
      // const updateCell = (rowIndex: number, value: string) => {
      //   treeList.current?.instance().cellValue(rowIndex, 'AuditTestCostMehthod', value);
      //   treeList.current?.instance().saveEditData();
      // };
    } else {
      notify('请先设置一个商品类别', 'error', 2000);
    }
  };
  useImperativeHandle(ref, () => ({
    showPop: async (treeListData: any) => {
      setIsViewSet(true);
      const dd: any = await getAccountInfo('get.BAS_Product.list', { dbname: dbname });
      if (dd.data?.length) {
        olddata.current = deepClone(
          dd.data.map((a: any) => {
            return { ...a, name: `${a.name}(${a.id})` };
          }),
        );
        setGoodsType(
          dd.data.map((a: any) => {
            return { ...a, name: `${a.name}(${a.id})` };
          }),
        );
      }

      LastUpdate.current = null;
    },
  }));

  const PriceCompont = () => {
    return (
      <TreeList
        ref={treeList}
        height={'100%'}
        keyExpr={'name'}
        // parentIdExpr={'typeParentID'}
        dataSource={goodsType}
        showRowLines={true}
        paging={{
          pageSize: 0,
        }}
        onSelectionChanged={(e: any) => {
          if (e.selectedRowsData.length) {
            SelectRow.current = e.selectedRowsData;
            setDis(false);
          } else {
            setDis(true);
          }
        }}
        // onRowUpdated={(e: any) => {
        //   debugger;
        //   LastUpdate.current = e.data;
        // }}
        // onRowUpdating={(e: any) => {
        //   debugger;
        //   LastUpdate.current = e.data;
        // }}
        onOptionChanged={(e) => {
          const value = e.value;
          if (value && typeof value === 'object') {
            debugger;
            if (value[0]?.data) {
              LastUpdate.current = value[0].data;
            }
          }
        }}
        searchPanel={{
          visible: true,
          searchVisibleColumnsOnly: true,
          width: 150,
        }}
        editing={{
          allowUpdating: true,
          mode: 'cell',
        }}
        selection={{ mode: 'multiple' }}
        columns={[
          {
            caption: '商品类别',
            dataField: 'name',
            allowEditing: false,
          },
          {
            caption: '计价方式',
            dataField: 'AuditTestCostMehthod',
            lookup: {
              dataSource: [
                { id: '月末一次加权平均法', name: '月末一次加权平均法' },
                { id: '先进先出法', name: '先进先出法' },
                { id: '移动加权平均法', name: '移动加权平均法' },
              ],
              valueExpr: 'id',
              displayExpr: 'name',
            },
          },
        ]}
        toolbar={{
          items: [
            {
              widget: 'dxButton',
              name: 'e',
              location: 'before',
              options: {
                text: '批量设置',
                type: 'default',
                disabled: Dis,
                onClick: OnClickButhSet,
              },
            },
            {
              name: 'searchPanel',
            },
            {
              location: 'after',
              widget: 'dxButton',
              cssClass: 'refreshButton_Style',
              options: {
                icon: 'iconfont icon-refresh',
                onClick: async () => {
                  const dd: any = await getAccountInfo('get.BAS_Product.list', { dbname: dbname });
                  if (dd?.data) {
                    setGoodsType(
                      dd.data.map((a: any) => {
                        return { ...a, name: `${a.name}(${a.id})` };
                      }),
                    );
                  }
                },
              },
            },
          ],
        }}
      ></TreeList>
    );
  };
  return (
    <>
      <DevPopup.Logic
        ref={InputRef}
        visible={IsViewAlert}
        title={'提示'}
        shading={true}
        onHiding={() => {
          setIsViewAlert(false);
        }}
        onOK={OKClickComputer}
        onCancel={() => {
          setIsViewAlert(false);
        }}
      >
        {() => <> 部分商品计价方式已修改，是否重算计价？</>}
      </DevPopup.Logic>
      <DevPopup.Logic
        ref={InputRef}
        visible={IsViewSet}
        height={'60vh'}
        // style={{ zIndex: '10000 !import' }}
        width={'32vw'}
        title={'商品计价方式设置'}
        shading={true}
        onHiding={() => {
          setIsViewSet(false);
        }}
        onOK={OnClickOK}
        onCancel={() => {
          setIsViewSet(false);
        }}
      >
        {PriceCompont}
      </DevPopup.Logic>
    </>
  );
});

export default TreeListPrice;
